package org.phoenixframework.api.sys.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.phoenixframework.common.tools.Constants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/14 23:50
 * description:
 */
public class SecurityUtils {

    public static String getUsername() {
        String userStr = getUserStr();
        if (null != userStr) {
            JSONObject userJsonObject = JSONObject.parseObject(userStr);
            return userJsonObject.getString("user_name");
        }
        return null;
    }

    public static Long getUserId() {
        String userStr = getUserStr();
        if (null != userStr) {
            JSONObject userJsonObject = JSONObject.parseObject(userStr);
            return userJsonObject.getLong("id");
        }
        return null;
    }

    private static String getUserStr() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if (null != httpServletRequest) {
            return httpServletRequest.getHeader(Constants.PHOENIX_OAUTH2_USER);
        }
        return null;
    }

    private static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

}
